package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.EditText;
import android.widget.ImageView;

import com.jdy.haoduoaiteacher.Constant;
import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.model.MemberType;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ImageUtils;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.StringInfoMatch;
import com.jdy.haoduoaiteacher.util.Tools;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;

import org.droidparts.annotation.inject.InjectView;

import java.util.HashMap;

//import com.jdy.haoduoaiteacher.R;

/**
 * 个人信息
 * 
 * @author Administrator
 * 
 */
@SuppressLint("InflateParams")
public class PersonalInformationActivity2 extends BaseActivity {

  private final static int REQUEST_PARENT_IMAGE = 100;
  private final static int REQUEST_BABY_BIRTHDAY = 104;

  private static final int REQUIRED_WIDTH = 300;
  private static final int REQUIRED_HEIGHT = 300;

  @InjectView(id = R.id.img_parent_avatar, click = true)
  private ImageView img_parent_avtar;
  @InjectView(id = R.id.edit_parent_desc, click = true)
  private EditText edit_parent_desc;
//  @InjectView(id = R.id.edit_class_desc, click = true)
//  private EditText edit_class_desc;
  @InjectView(id = R.id.edit_parent_nickname, click = true)
  private EditText edit_parent_nickname;

  private AlertDialog.Builder builder;
  private AlertDialog alertDialog;

  private LeUser mLeUser, mLeUserGetted; //*/;
  private Uri ParentUri;


  private String parentAvatar;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.personal_information_layout2_teacher);
    setTitle("个人信息");
    initView();
  }

  private void getParentInfo() {
    if (mLeUser != null) {
      if (mLeUser.member_types!=null && !mLeUser.member_types.isEmpty()) {
        for (MemberType item : mLeUser.member_types) {
          if (item.type_id ==1) {
            if (Tools.isEmpty(item.nick_name)) {
//              edit_parent_nickname.setText("好多爱教师");
            }
//              edit_parent_nickname.setText(item.nick_name);

//            if (Tools.isEmpty(item.desc)) {
//              edit_parent_desc.setText("武汉好多爱幼儿园");
//            } else {
//              edit_parent_desc.setText(item.desc);
//            }

//            edit_class_desc.setText(item.desc2);

            break;
          }
        }
      }
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
  }

  private final StringInfoMatch stringMatch = new StringInfoMatch();

  private void initView() {
//    mUprightButton.setText("完成");
//    mUprightButton.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);

//设置头像 昵称 学校
    String icon = SPUtil.getString(this, "icon", "");

    if (!TextUtils.isEmpty(icon)) {
      Picasso.with(this).load(icon).into(img_parent_avtar);
    }

    //设置昵称
    String nickname = SPUtil.getString(this, "name", "");
    edit_parent_nickname.setText(nickname);

    //设置学校
    String school = SPUtil.getString(this, "schoolName", "");
    edit_parent_desc.setText(school);

    mLeUser = MyTeacherApp.getInstance().getUserTeacher();

    SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);
    String parentImagePath = prefs.getString(Constant.PARENT_AVATAR, "");
    if (Tools.isNotEmpty(parentImagePath)) {
      ParentUri = Uri.parse(parentImagePath);
//      setImageViewContent(img_parent_avtar, ParentUri);
    } else {
      if (mLeUser != null && mLeUser.callname != null) {
        if (mLeUser.callname.contains("爸爸") || mLeUser.callname.contains("爷爷")
            || mLeUser.callname.contains("外公")) {
//          img_parent_avtar
//              .setImageResource(R.drawable.defaut_parent_avtar_male);
        } else {
//          img_parent_avtar
//              .setImageResource(R.drawable.defaut_parent_avtar_female);
        }
      }
    }

    getParentInfo();

    mUprightButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        v.startAnimation(mPressedAnimation);
        mPressedAnimation.setAnimationListener(new AnimationListener() {
          @Override
          public void onAnimationStart(Animation animation) {

          }

          @Override
          public void onAnimationRepeat(Animation animation) {

          }

          @Override
          public void onAnimationEnd(Animation animation) {
//            String newParentName = edit_parent_nickname.getText().toString();
//            String schoolName = edit_parent_desc.getText().toString();
//            String clasName = edit_class_desc.getText().toString();

//            if (Tools.isEmpty(newParentName) || "null".equals(newParentName)) {
            //  edit_parent_nickname.setText("用户" + mLeUser.id);
//            } else {
//              edit_parent_nickname.setText(newParentName);
             // edit_class_desc.setText(clasName);
//            }


//            if (Tools.isEmpty(newParentName)) {
//             toastShow("请输入呢称!");
//              return;
//            }
//
//            if (Tools.isEmpty(schoolName)) {
//              toastShow("请输入学校名!");
//              return;
//            }
//
//            if (Tools.isEmpty(clasName)) {
//              toastShow("请输入班级名!");
//              return;
//            }
//
//            if (mLeUser != null) {
//              for (MemberType item : mLeUser.member_types) {
//                if (item.type_id ==1) {
//                  item.nick_name = newParentName;
//                  item.desc = schoolName;
//                  item.desc2 = clasName;
//                  break;
//                }
//              }
//
//            }
            MyTeacherApp.getInstance().setUser(mLeUser);
            Tools.saveLeUser(mLeUser);

            updateParentInfo();
          }
        });
      }
    });

//    img_parent_avtar.setOnClickListener(new View.OnClickListener() {
//      @Override
//      public void onClick(View v) {
//        Intent intent = new Intent(new Intent(
//            PersonalInformationActivity2.this, SelectPicPopupWindow.class));
//        intent.putExtra("avatar_path",
//            PathUtil.getElderAvatarPath(getApplicationContext()));
//        startActivityForResult(intent, REQUEST_PARENT_IMAGE);
//        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
//      }
//    });
  }

  private void updateParentInfo() {
    if (Tools.isNotEmpty(edit_parent_nickname.getText().toString().trim())) {
      new CustomAsyncTask(this, new IAsyncTask() {
        @Override
        public void onRecieveData(Activity activity, ResponseResult result) {
          if (result.isSuccess()) {
           // toastShow(result.data);
            LeUser lu = JsonSerializer.getInstance().deserialize(result.data,
                    LeUser.class);

            if (lu != null) {
              MyTeacherApp.getInstance().setUser(lu);
            }

            dismissLoading();

            Intent it = new Intent();
            it.setAction("updatepersonalinfo");
            sendBroadcast(it);

            finish();
          } else {
              if (Tools.isNotEmpty(result.data)) {
                  toastShow(result.data);
              }
          }
        }

        @Override
        public ResponseResult doInbackground(Activity activity) {
          HashMap<String, Object> param_ = new HashMap<String, Object>();
          param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
          param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
          if (Tools.isNotEmpty(parentAvatar)) {
            param_.put("avatar", parentAvatar);
          }
//          if (Tools.isNotEmpty(edit_parent_nickname.getText().toString()
//                  .trim())) {
//            param_.put("nick_name", edit_parent_nickname.getText().toString()
//                    .trim());
//          }
//          if (Tools.isNotEmpty(edit_parent_desc.getText().toString().trim())) {
//            param_.put("desc", edit_parent_desc.getText().toString().trim());
//          }
//          if (Tools.isNotEmpty(edit_class_desc.getText().toString().trim())) {
//            param_.put("desc2", edit_class_desc.getText().toString().trim());
//          }

          return HttpUtils.startRequest(HttpUtils.API_URL + "/api/2.0/teacher/update_profile"
              , param_, HttpUtils.TAG_POST_REQUEST);
        }
      }).execute("请检查网络连接!");

    }
  }

  private void uploadParentAvatar(final String filePath) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result != null) {
          parentAvatar = result.data;
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_MOBILE_I, mLeUser.id);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_MODULE_I, "teacher/avatar");

        return HttpUtils.startUploadRequest(HttpUtils.API_URL
            + HttpUtils.UPLOAD_AVATAR_METHOD_POST, param_, "Filedata",
            filePath, HttpUtils.TAG_POST_REQUEST);
      }
    }).execute("请检查网络连接!");
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
      Intent returnedIntent) {
    super.onActivityResult(requestCode, resultCode, returnedIntent);
    switch (requestCode) {
    case REQUEST_PARENT_IMAGE:
      if (resultCode == RESULT_OK) {
        this.ParentUri = Uri.parse(returnedIntent.getExtras()
            .getString("image"));
//        setImageViewContent(img_parent_avtar, this.ParentUri);
//        uploadParentAvatar(this.ParentUri.getPath());
        storeUserInfo(Constant.PARENT_AVATAR, this.ParentUri.toString());

        Intent it = new Intent();
        it.setAction("updateparentheadimage");
        sendBroadcast(it);
      }
      break;
    case REQUEST_BABY_BIRTHDAY:
      break;
    }
  }

  private void storeUserInfo(String key, String value) {
    SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);
    prefs.edit().putString(key, value).apply();
  }

  private Bitmap setImageViewContent(ImageView source, Uri original) {
    if (original != Uri.EMPTY) {
      Bitmap originalBitmap = ImageUtils.getBitmapFromUri(this, original);
      if (originalBitmap != null) {
        Bitmap bm = ImageUtils.scaleCropToFit(originalBitmap, REQUIRED_WIDTH,
            REQUIRED_HEIGHT, true);
        source.setImageURI(null);
        if (bm != null) {
          source.setImageBitmap(bm);
        }
        return bm;
      }
    }
    return null;
  }
}
